package com.icinfo.cloud.provider.common.utils;

import com.icinfo.framework.tools.utils.HttpClientUtil;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http请求工具封装.
 */
public class HttpUtils extends HttpClientUtil {


    /**
     * 判断是否Ajax请求
     *
     * @param request 请求/CaseMainInfoDto.java
     * @return ajax请求：true 否则 false
     */
    public static boolean isAjax(HttpServletRequest request) {
        // 判定是否为异步请求，非异步请求直接进入error页面
        return ((request.getHeader("accept") != null && request.getHeader("accept").indexOf("application/json") > -1)
                || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1));
    }

    /**
     * 异步请求异常处理
     *
     * @param response 请求响应
     * @param errorInfo 错误信息
     * @param httpStatus http状态码
     * @throws Exception
     */
    public static void writeError(HttpServletResponse response, String errorInfo, int httpStatus) throws Exception {
        PrintWriter writer = null;
        try {
            // 设置响应字符集
            response.setContentType("text/html; charset=utf-8");
            // 设置HTTP响应状态码
            response.setStatus(httpStatus);
            writer = response.getWriter();
            writer.write(errorInfo);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }


    public static String doHttpPost(String url, Map<String, Object> paraMap) throws Exception {
        String msgRet = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //访问归结接口
        HttpPost post = new HttpPost(url);
        try {
            // 请求类型：x-www-form-urlencoded
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                    nvps, Consts.UTF_8);
            entity.setContentEncoding("UTF-8");
            entity.setContentType(ContentType.APPLICATION_FORM_URLENCODED
                    .getMimeType());
            post.setEntity(entity);
            msgRet = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            httpClient.close();
        }
        return msgRet;
    }


    /**
     * 传送json类型的post请求
     *
     * @param url
     * @param json
     * @return String
     */
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}

